//
//  PhotoDetailViewController.m
//  Gruphoto
//
//  Created by Thao Nguyen Huy on 1/10/13.
//  Copyright (c) 2013 CNC Software. All rights reserved.
//

#import "PhotoDetailViewController.h"
#import "PhotoCommentView.h"
#import "MakeCommentViewController.h"
#import "PhotoLargeView.h"
#import "GruphotoAppDelegate.h"
#import "User.h"

@interface PhotoDetailViewController ()

@end

@implementation PhotoDetailViewController
@synthesize photoScrollView, deviders, authorNameLabel, numberLikesLabel, authorImageView;
@synthesize commentsContainerView, imageContainerScrollView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        UIImageView *titleImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"title_gruphoto.png"]];
        self.navigationItem.titleView = titleImageView;
        [titleImageView release];
        
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [backButton setBounds:CGRectMake(0, 0, 51, 30)];
        [backButton setBackgroundImage:[UIImage imageNamed:@"button_back.png"] forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(backButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
        self.navigationItem.leftBarButtonItem = backButtonItem;
        [backButtonItem release];        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"background_navigation_bar.png"]
                                                      forBarMetrics:UIBarMetricsDefault];
    }
    self.view.backgroundColor = [UIColor colorWithRed:226/255.0 green:231/255.0 blue:237/255.0 alpha:1.0];
    authorNameLabel.textColor = [UIColor colorWithRed:107/255.0 green:120/255.0 blue:130/255.0 alpha:1.0];
    numberLikesLabel.textColor = [UIColor colorWithRed:107/255.0 green:120/255.0 blue:130/255.0 alpha:1.0];
    for (UIView *devider in deviders) {
        if (devider.tag == 1) {
            devider.backgroundColor = [UIColor colorWithRed:129/255.0 green:146/255.0 blue:159/255.0 alpha:1.0];
        }
        else {
            devider.backgroundColor = [UIColor colorWithRed:190/255.0 green:191/255.0 blue:193/255.0 alpha:1.0];
        }
    }
    [self setContentSizeForImageContainerScrollView];
    [self displayDetail];
    [self showContents];
    liked = NO;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.photoScrollView = nil;
    self.deviders = nil;
    self.authorImageView = nil;
    self.authorNameLabel = nil;
    self.numberLikesLabel = nil;
    self.commentsContainerView = nil;
    self.imageContainerScrollView = nil;
    _info = nil;
}

- (void)dealloc {
    [authorNameLabel release];
    [authorImageView release];
    [numberLikesLabel release];
    [photoScrollView release];
    [commentsContainerView release];
    [deviders release];
    [imageContainerScrollView release];
    [_info release];
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Action methods
- (IBAction)backButtonPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)likeButtonPressed:(id)sender {
    liked = !liked;   
    UIButton *button = (UIButton *)sender;
    NSString *normalName = @"segment_like_normal.png";
    UIImage *normalImage = [UIImage imageNamed:normalName];
    NSString *activeName = @"segment_like_active.png";
    UIImage *activeImage = [UIImage imageNamed:activeName];
    if (liked) {
        [button setImage:activeImage forState:UIControlStateNormal];
        numberLikesLabel.text = [NSString stringWithFormat:@"%d",[numberLikesLabel.text intValue]+1];
    }
    else {
        [button setImage:normalImage forState:UIControlStateNormal];
        numberLikesLabel.text = [NSString stringWithFormat:@"%d",[numberLikesLabel.text intValue]-1];
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:[GruphotoAppDelegate sharedDelegate].loggedInUser.token forKey:kUserToken];
    [params setObject:[_info objectForKey:kImageId] forKey:kImageId];
    [params setObject:[NSNumber numberWithBool:liked] forKey:kVote];
    NSLog(@"params: %@", params);
    [TNHRequestHelper sendPostRequest:kGetJoinableEventsUrl
                              withTag:RequestTagGetJoinableEvents
                               params:params
                             delegate:self];
}

- (IBAction)commentButtonPressed:(id)sender {
    MakeCommentViewController *makeCommentViewController = [[MakeCommentViewController alloc] initWithNibName:@"MakeCommentViewController" bundle:nil];
    [self.navigationController pushViewController:makeCommentViewController animated:YES];
    [makeCommentViewController release];
}

- (IBAction)shareButtonPressed:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Share this photo by"
                                                             delegate:self
                                                    cancelButtonTitle:@"Cancel"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"Facebook", @"Twitter", @"Tumblr", @"Email", nil];
    [actionSheet showInView:self.view];
    [actionSheet release];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    NSLog(@"button index; %d", buttonIndex);
    if (buttonIndex != actionSheet.cancelButtonIndex) {
        switch (buttonIndex) {
            case 0: { // share photo via Facebook
                [FBRequestConnection startForUploadPhoto:nil completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                    
                }];
                break;
            }
            case 1:
                break;
            case 2:
                break;
            case 3: { // Share photo via email
                if ([MFMailComposeViewController canSendMail]) {
                    MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
                    mailComposer.mailComposeDelegate = self;
                    [mailComposer setSubject:[NSString stringWithFormat:@"A beautiful photo in Gruphoto event"]];
                    NSString *body = @"Hey you! please see and enjoin this photo";
                    [mailComposer setMessageBody:body isHTML:NO];
                    // TODO: attach photo
//                    [mailComposer addAttachmentData:<#(NSData *)#> mimeType:<#(NSString *)#> fileName:<#(NSString *)#>]
                    [self presentModalViewController:mailComposer animated:YES];
                    [mailComposer release];
                }
                else {
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Warning message"
                                                                        message:@"Email is not set on device"
                                                                       delegate:self
                                                              cancelButtonTitle:@"OK"
                                                              otherButtonTitles: nil];
                    [alertView show];
                    [alertView release];
                }
                break;
            }
            default:
                break;
        }
    }
}

#pragma mark - MFMailComposeViewControllerDelegate & MFMessageComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    switch (result) {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail compose cancelled.");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail compose saved.");
            break;
        case MFMailComposeResultSent: {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Gruphoto message"
                                                                message:@"Email was sent to your friend"
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
            [alertView show];
            [alertView release];
            break;
        }
        case MFMailComposeResultFailed: {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error message"
                                                                message:@"Failure to send email"
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
            [alertView show];
            [alertView release];
            break;
        }
        default:
            break;
    }
    [controller dismissModalViewControllerAnimated:YES];
}

#pragma mark - Custom methods
- (void)showContents {
    for (int i = 0; i < 3; i++) {
        PhotoLargeView *view = [PhotoLargeView viewFromNib];
        CGRect frame = view.frame;
        frame.origin.x = i * 320;
        view.frame = frame;
        NSLog(@"Add a photo at %f, %f", frame.origin.x, frame.origin.y);
        [imageContainerScrollView addSubview:view];
    }
    imageContainerScrollView.contentSize = CGSizeMake(3 * 320, 324);
    
    float y = 0;
    for (int i = 0; i < 5; i++) {
        PhotoCommentView *view = [PhotoCommentView viewFromNib];
        CGRect frame = view.frame;
        frame.origin.y = y;
        view.frame = frame;
        [commentsContainerView addSubview:view];
        y += frame.size.height;
    }
    photoScrollView.contentSize = CGSizeMake(320, 800);
}

#pragma mark - display detail
-(void)displayDetail{
    NSString *link = [NSString stringWithFormat:@"%@%@",kServerUrl,[_info objectForKey:kSource]];
    NSLog(@"link = %@",link);
    UIImageView *imgV = [[[UIImageView alloc] initWithFrame:CGRectMake(imageContainerScrollView.frame.size.width*_currentIndexOfImage, 0, imageContainerScrollView.frame.size.width,imageContainerScrollView.frame.size.height)] autorelease];
    [imgV setImageWithURL:[NSURL URLWithString:link] placeholderImage:nil];
    [imageContainerScrollView addSubview:imgV];
    [imageContainerScrollView setContentOffset:CGPointMake(_currentIndexOfImage*imageContainerScrollView.frame.size.width, 0)];
    numberLikesLabel.text = [[_info objectForKey:kNumLike] stringValue];
    authorNameLabel.text = [[_info objectForKey:@"creator"] objectForKey:kName];
    [self setContentSizeForImageContainerScrollView];
}

#pragma mark - ASIHTTPRequestDelegate
- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"data: %@", request.responseString);
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    NSLog(@"Failed: %@", request.error.description);
}
#pragma mark - set contentsize,reload for imageContainerScrollView
- (void)setContentSizeForImageContainerScrollView{
    imageContainerScrollView.contentSize = CGSizeMake([_listImagesData count]*imageContainerScrollView.frame.size.width,imageContainerScrollView.frame.size.height );
    imageContainerScrollView.frame = CGRectMake(imageContainerScrollView.frame.origin.x, imageContainerScrollView.frame.origin.y, imageContainerScrollView.frame.size.width, 324);
}
- (void)reloadViewForImageContainerScrollView{
    NSArray *listSubView = imageContainerScrollView.subviews;
    for (int i=0; i<[listSubView count]; i++) {
        UIView *view =[listSubView objectAtIndex:i];
        if ([view isKindOfClass:[UIImageView class]]) {
            [view removeFromSuperview];
        }
    }
    [_info setDictionary:[_listImagesData objectAtIndex:_currentIndexOfImage]];
    [self displayDetail];
}
#pragma mark - scrollView delegate
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    int newIndex = scrollView.contentOffset.x/scrollView.frame.size.width;
    if (newIndex!=_currentIndexOfImage) {
        _currentIndexOfImage = newIndex;
        NSLog(@"load image detail at index = %d",_currentIndexOfImage);
        [self reloadViewForImageContainerScrollView];
    }
}
@end
